<template>
  <div class="interest-community-page">
    <div class="back-btn-wrapper">
      <el-button type="text" @click="goBack" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>
    <div class="page-header">
      <div class="header-content">
        <h1>兴趣社群</h1>
        <p>基于兴趣的社群交流，丰富校园文化生活</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          创建社群
        </el-button>
        <el-button @click="showSearchDialog = true">
          <el-icon><Search /></el-icon>
          搜索社群
        </el-button>
      </div>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="community-tabs">
      <el-tab-pane label="我加入的社群" name="joined">
        <div class="communities-container">
          <div v-if="joinedCommunities.length === 0" class="empty-state">
            <el-icon :size="64"><UserGroup /></el-icon>
            <h3>您还没有加入任何兴趣社群</h3>
            <p>搜索并加入兴趣社群，开始您的社交之旅吧！</p>
            <el-button type="primary" @click="showSearchDialog = true">
              搜索社群
            </el-button>
          </div>
          
          <div v-else class="communities-grid">
            <div 
              class="community-card" 
              v-for="community in joinedCommunities" 
              :key="community.id"
              @click="viewCommunityDetail(community)"
            >
              <div class="community-header">
                <h3>{{ community.name }}</h3>
                <el-tag size="small" type="primary">{{ community.memberCount }}人</el-tag>
              </div>
              <div class="community-info">
                <p class="community-desc">{{ community.description || '暂无描述' }}</p>
                <div class="community-meta">
                  <el-tag size="small" type="info">{{ community.category }}</el-tag>
                </div>
                <div class="community-creator">
                  <el-icon><User /></el-icon>
                  <span>创建者：{{ community.creatorName }}</span>
                </div>
              </div>
              <div class="community-actions">
                <el-button size="small" @click.stop="viewMembers(community)">
                  查看成员
                </el-button>
                <el-button size="small" @click.stop="viewPosts(community)">
                  查看帖子
                </el-button>
                <!-- 只有非创建者可以退出社群 -->
                <el-button 
                  v-if="String(community.creatorId) !== userInfo.id" 
                  size="small" 
                  type="danger" 
                  @click.stop="leaveCommunity(community)"
                >
                  退出
                </el-button>
                <el-button 
                  v-if="String(community.creatorId) === userInfo.id" 
                  size="small" 
                  type="danger" 
                  @click.stop="deleteCommunity(community)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="我创建的社群" name="created">
        <div class="communities-container">
          <div v-if="createdCommunities.length === 0" class="empty-state">
            <el-icon :size="64"><UserGroup /></el-icon>
            <h3>您还没有创建任何兴趣社群</h3>
            <p>创建兴趣社群，邀请志同道合的朋友加入！</p>
            <el-button type="primary" @click="showCreateDialog = true">
              创建社群
            </el-button>
          </div>
          
          <div v-else class="communities-grid">
            <div 
              class="community-card" 
              v-for="community in createdCommunities" 
              :key="community.id"
              @click="viewCommunityDetail(community)"
            >
              <div class="community-header">
                <h3>{{ community.name }}</h3>
                <el-tag size="small" type="success">创建者</el-tag>
              </div>
              <div class="community-info">
                <p class="community-desc">{{ community.description || '暂无描述' }}</p>
                <div class="community-meta">
                  <el-tag size="small" type="info">{{ community.category }}</el-tag>
                </div>
                <div class="community-stats">
                  <span>{{ community.memberCount }} 名成员</span>
                  <span>{{ community.postCount }} 个帖子</span>
                </div>
              </div>
              <div class="community-actions">
                <el-button size="small" @click.stop="viewMembers(community)">
                  管理成员
                </el-button>
                <el-button size="small" @click.stop="viewPosts(community)">
                  查看帖子
                </el-button>
                <el-button size="small" type="danger" @click.stop="deleteCommunity(community)">
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建社群对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      title="创建兴趣社群" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="createFormRef" 
        :model="createForm" 
        :rules="createRules" 
        label-width="100px"
      >
        <el-form-item label="社群名称" prop="name">
          <el-input 
            v-model="createForm.name" 
            placeholder="请输入社群名称"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="社群分类" prop="category">
          <el-select v-model="createForm.category" placeholder="请选择社群分类">
            <el-option label="科研项目组" value="科研项目组" />
            <el-option label="运动健身" value="运动健身" />
            <el-option label="音乐艺术" value="音乐艺术" />
            <el-option label="编程技术" value="编程技术" />
            <el-option label="读书学习" value="读书学习" />
            <el-option label="游戏娱乐" value="游戏娱乐" />
            <el-option label="摄影摄像" value="摄影摄像" />
            <el-option label="美食烹饪" value="美食烹饪" />
            <el-option label="旅行户外" value="旅行户外" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="社群描述" prop="description">
          <el-input 
            v-model="createForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入社群描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createCommunity" :loading="creating">
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 搜索社群对话框 -->
    <el-dialog 
      v-model="showSearchDialog" 
      title="搜索兴趣社群" 
      width="600px"
    >
      <div class="search-section">
        <el-form @submit.prevent="searchCommunities">
          <el-form-item>
            <el-select 
              v-model="searchCategory" 
              placeholder="选择分类搜索"
              style="width: 100%"
              @change="searchCommunities"
            >
              <el-option label="全部分类" value="" />
              <el-option label="科研项目组" value="科研项目组" />
              <el-option label="运动健身" value="运动健身" />
              <el-option label="音乐艺术" value="音乐艺术" />
              <el-option label="编程技术" value="编程技术" />
              <el-option label="读书学习" value="读书学习" />
              <el-option label="游戏娱乐" value="游戏娱乐" />
              <el-option label="摄影摄像" value="摄影摄像" />
              <el-option label="美食烹饪" value="美食烹饪" />
              <el-option label="旅行户外" value="旅行户外" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-if="searchResults.length > 0" class="search-results">
        <div class="result-card" v-for="community in searchResults" :key="community.id">
          <div class="result-header">
            <h4>{{ community.name }}</h4>
            <el-tag size="small" type="info">{{ community.category }}</el-tag>
          </div>
          <p>{{ community.description || '暂无描述' }}</p>
          <div class="result-meta">
            <span>创建者：{{ community.creatorName }}</span>
            <span>{{ community.memberCount }}人</span>
            <span>{{ community.postCount }}个帖子</span>
          </div>
          <div class="result-actions">
            <el-button 
              v-if="!isJoined(community.id)" 
              type="primary" 
              @click="joinCommunity(community)"
              :loading="joining"
            >
              加入社群
            </el-button>
            <el-tag v-else type="success">已加入</el-tag>
          </div>
        </div>
      </div>
      
      <div v-else-if="hasSearched" class="empty-search">
        <p>未找到相关社群</p>
      </div>
      
      <template #footer>
        <el-button @click="showSearchDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 成员列表对话框 -->
    <el-dialog 
      v-model="showMembersDialog" 
      :title="`${currentCommunity?.name} - 成员列表`" 
      width="600px"
    >
      <div v-if="members.length === 0" class="empty-state">
        <p>暂无成员</p>
      </div>
      
      <div v-else class="members-list">
        <div 
          class="member-item" 
          v-for="member in members" 
          :key="member.id"
        >
          <div class="member-info">
            <el-avatar :size="40">
              {{ member.userName.charAt(0) }}
            </el-avatar>
            <div class="member-details">
              <div class="member-name">{{ member.userName }}</div>
              <div class="member-role">
                <el-tag size="small" :type="member.joinType === 'CREATOR' ? 'success' : 'info'">
                  {{ member.joinType === 'CREATOR' ? '创建者' : member.userRole === 'TEACHER' ? '教师' : '学生' }}
                </el-tag>
              </div>
            </div>
          </div>
          <div class="member-time">
            {{ formatTime(member.joinTime) }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  UserGroup,
  User,
  ArrowLeft
} from '@element-plus/icons-vue'
import { interestCommunityApi } from '@/api/social'

export default {
  name: 'InterestCommunityPage',
  components: {
    Plus,
    Search,
    UserGroup,
    User,
    ArrowLeft
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    
    // 用户信息
    const userInfo = computed(() => store.state.user.userInfo)
    
    // 标签页
    const activeTab = ref('joined')
    
    // 社群数据
    const joinedCommunities = ref([])
    const createdCommunities = ref([])
    
    // 对话框状态
    const showCreateDialog = ref(false)
    const showSearchDialog = ref(false)
    const showMembersDialog = ref(false)
    
    // 创建表单
    const createFormRef = ref()
    const createForm = reactive({
      name: '',
      category: '',
      description: ''
    })
    
    const createRules = {
      name: [
        { required: true, message: '请输入社群名称', trigger: 'blur' },
        { min: 2, max: 50, message: '社群名称长度在2-50个字符', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择社群分类', trigger: 'change' }
      ]
    }
    
    // 搜索相关
    const searchCategory = ref('')
    const searchResults = ref([])
    const hasSearched = ref(false)
    const joining = ref(false)
    const creating = ref(false)
    
    // 成员相关
    const currentCommunity = ref(null)
    const members = ref([])
    
    // 加载数据
    const loadData = async () => {
      try {
        // 加载加入的社群
        const joinedResponse = await interestCommunityApi.getMyJoinedCommunities()
        if (joinedResponse.code === 200 && joinedResponse.data) {
          joinedCommunities.value = joinedResponse.data
        }
        
        // 加载创建的社群
        const createdResponse = await interestCommunityApi.getMyCreatedCommunities()
        if (createdResponse.code === 200 && createdResponse.data) {
          createdCommunities.value = createdResponse.data
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      }
    }
    
    // 创建社群
    const createCommunity = async () => {
      try {
        await createFormRef.value.validate()
        creating.value = true
        
        const response = await interestCommunityApi.createCommunity(createForm)
        if (response.code === 200) {
          ElMessage.success('社群创建成功')
          showCreateDialog.value = false
          // 重置表单
          Object.keys(createForm).forEach(key => {
            createForm[key] = ''
          })
          // 重新加载数据
          await loadData()
        } else {
          ElMessage.error(response.message || '创建失败')
        }
      } catch (error) {
        console.error('创建社群失败:', error)
        ElMessage.error('创建社群失败')
      } finally {
        creating.value = false
      }
    }
    
    // 搜索社群
    const searchCommunities = async () => {
      try {
        hasSearched.value = true
        if (searchCategory.value) {
          const response = await interestCommunityApi.getCommunitiesByCategory(searchCategory.value)
          if (response.code === 200 && response.data) {
            searchResults.value = response.data
          } else {
            searchResults.value = []
          }
        } else {
          const response = await interestCommunityApi.getAllCommunities()
          if (response.code === 200 && response.data) {
            searchResults.value = response.data
          } else {
            searchResults.value = []
          }
        }
      } catch (error) {
        console.error('搜索失败:', error)
        ElMessage.error('搜索失败')
      }
    }
    
    // 加入社群
    const joinCommunity = async (community) => {
      try {
        joining.value = true
        const response = await interestCommunityApi.joinCommunity(community.id)
        if (response.code === 200) {
          ElMessage.success('成功加入社群')
          await loadData()
          // 更新搜索结果中的状态
          const index = searchResults.value.findIndex(c => c.id === community.id)
          if (index !== -1) {
            searchResults.value[index].isJoined = true
          }
        } else {
          ElMessage.error(response.message || '加入失败')
        }
      } catch (error) {
        console.error('加入社群失败:', error)
        ElMessage.error('加入社群失败')
      } finally {
        joining.value = false
      }
    }
    
    // 退出社群
    const leaveCommunity = async (community) => {
      try {
        await ElMessageBox.confirm(
          `确定要退出社群"${community.name}"吗？`,
          '确认退出',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await interestCommunityApi.leaveCommunity(community.id)
        if (response.code === 200) {
          ElMessage.success('成功退出社群')
          await loadData()
        } else {
          ElMessage.error(response.message || '退出失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('退出社群失败:', error)
          ElMessage.error('退出社群失败')
        }
      }
    }
    
    // 删除社群
    const deleteCommunity = async (community) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除社群"${community.name}"吗？删除后无法恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await interestCommunityApi.deleteCommunity(community.id)
        if (response.code === 200) {
          ElMessage.success('社群删除成功')
          await loadData()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除社群失败:', error)
          ElMessage.error('删除社群失败')
        }
      }
    }
    
    // 查看成员
    const viewMembers = async (community) => {
      try {
        currentCommunity.value = community
        const response = await interestCommunityApi.getCommunityMembers(community.id)
        if (response.code === 200) {
          members.value = response.data
          showMembersDialog.value = true
        } else {
          ElMessage.error('获取成员列表失败')
        }
      } catch (error) {
        console.error('获取成员列表失败:', error)
        ElMessage.error('获取成员列表失败')
      }
    }

    // 查看帖子
    const viewPosts = (community) => {
      router.push(`/social/community-posts/${community.id}`)
    }

    // 查看社群详情
    const viewCommunityDetail = (community) => {
      // 这里可以跳转到社群详情页面
      ElMessage.info(`查看社群：${community.name}`)
    }
    
    // 检查是否已加入
    const isJoined = (communityId) => {
      return joinedCommunities.value.some(community => community.id === communityId)
    }
    
    // 格式化时间
    const formatTime = (time) => {
      const date = new Date(time)
      return date.toLocaleString()
    }

    // 返回社交互动页面
    const goBack = () => {
      router.push('/social')
    }
    
    onMounted(() => {
      loadData()
    })
    
    return {
      userInfo,
      activeTab,
      joinedCommunities,
      createdCommunities,
      showCreateDialog,
      showSearchDialog,
      showMembersDialog,
      createFormRef,
      createForm,
      createRules,
      searchCategory,
      searchResults,
      hasSearched,
      joining,
      creating,
      currentCommunity,
      members,
      createCommunity,
      searchCommunities,
      joinCommunity,
      leaveCommunity,
      deleteCommunity,
      viewMembers,
      viewPosts,
      viewCommunityDetail,
      isJoined,
      formatTime,
      goBack
    }
  }
}
</script>

<style scoped>
.interest-community-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.back-btn-wrapper {
  margin-bottom: 20px;
  margin-left: -8px;
}

.back-btn {
  color: var(--el-color-primary);
  font-size: 15px;
  font-weight: bold;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 4px 12px 4px 4px;
  border-radius: 6px;
  background: transparent;
  transition: background 0.2s, color 0.2s;
}

.back-btn:hover {
  background: rgba(64, 158, 255, 0.08);
  color: var(--el-color-primary-dark);
  text-decoration: none;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header-content h1 {
  font-size: 28px;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.header-content p {
  color: var(--el-text-color-regular);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.community-tabs {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.communities-container {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--el-text-color-secondary);
}

.empty-state h3 {
  margin: 16px 0 8px;
  color: var(--el-text-color-primary);
}

.empty-state p {
  margin-bottom: 20px;
}

.communities-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.community-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.community-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.community-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.community-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.community-info {
  margin-bottom: 16px;
}

.community-desc {
  color: var(--el-text-color-regular);
  margin: 0 0 12px 0;
  line-height: 1.5;
}

.community-meta {
  margin-bottom: 8px;
}

.community-creator,
.community-stats {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.community-stats {
  gap: 16px;
}

.community-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.search-section {
  margin-bottom: 20px;
}

.search-results {
  max-height: 400px;
  overflow-y: auto;
}

.result-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.result-header h4 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.result-meta {
  display: flex;
  gap: 16px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin: 8px 0;
}

.result-actions {
  margin-top: 12px;
}

.empty-search {
  text-align: center;
  padding: 40px;
  color: var(--el-text-color-secondary);
}

.members-list {
  max-height: 400px;
  overflow-y: auto;
}

.member-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.member-item:last-child {
  border-bottom: none;
}

.member-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.member-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.member-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.member-time {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
</style> 